import java.util.concurrent.TimeUnit;

//所谓的死锁就是线程一拥有锁1，线程二拥有锁2，
// 双方在拥有自身锁的同时尝试获取对方的锁，最终两个线程就会进入无线等待的状态，
// 这就是死锁。
public class ThreadDemo2 {
    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName() +
                        ":已经获取到锁1");
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() +
                            ":获取到锁2");
                }
            }
        }, "t1");
        t1.start();
        Thread t2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "：获取到锁2");
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "：获取到锁1");
                }
            }
        }, "t2");
        t2.start();
    }
}